import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: {
      keepAlive: true
    }
  },
  {
    path: '/cates',
    name: 'Cates',
    component: () => import('@/views/Cates'),
    meta: {
      keepAlive: true
    }
  },
  {
    path: '/cart',
    name: 'Cart',
    component: () => import('@/views/Cart'),
    meta: {
      keepAlive: false
    }
  },
  {
    path: '/mine',
    name: 'Mine',
    component: () => import('@/views/Mine'),
    meta: {
      needLogin: true,
      keepAlive: false
    }
  },
  {
    path: '/detail/:id',
    name: 'Detail',
    component: () => import('@/views/Detail'),
    meta: {
    }
  },
  {
    path: '/itemList/:cateId',
    name: 'itemList',
    component: () => import('@/views/ItemList'),
    meta: {
    }
  },
  {
    path: '/order',
    name: 'order',
    component: () => import('@/views/Order'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/addressLists',
    name: 'addressLists',
    component: () => import('@/views/AddressLists'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/addContact',
    name: 'addContact',
    component: () => import('@/views/AddContact'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/editContact/:index',
    name: 'editContact',
    component: () => import('@/views/EditContact'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('@/views/Search'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/searchResult',
    name: 'searchResult',
    component: () => import('@/views/SearchResult'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login'),
    meta: {
    }
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  // 判断 是不是去登录和注册
  if (to.fullPath === '/login' || to.fullPath === 'register') {
    next()
  } else {
    // 判断是否需要登录权限
    if (to.meta.needLogin) {
      // 判断是否登录
      const accessToken = localStorage.getItem('accessToken')
      if (accessToken) {
        next()
      } else {
        next({ path: '/login', query: { path: to.fullPath } })
      }
    } else {
      next()
    }
  }

  // 需要 判断是否登录
})
export default router
